package com.pricy.me;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pricy.me.adapters.CategoryChoiceAdapter;
import com.pricy.me.model.Category;
import com.pricy.me.model.CategoryIcon;
import com.pricy.me.model.Product;
import com.pricy.me.model.TempData;
import com.pricy.me.model.User;

public class AddProductDialog extends Dialog{

	private ImageView photo;
	private Bitmap picture;
	private Button btnAjouter;
	// private Button btnCurrency;
	private EditText titre;
	private EditText prix;
	private CheckBox owner;
	private Context context;
	private Bitmap pictureThumb;
	private Handler hm;
	private ProgressDialog mProgress;
	/*
	 * Defintion des variable  finaux pour traiter les strings
	 */
	
	
	public AddProductDialog(final Context context) {
		super(context);
		this.context = context;
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.add);
		mProgress		= new ProgressDialog(context);
		titre = (EditText) findViewById(R.id.addEtTitre);
		prix = (EditText) findViewById(R.id.idBonneaffaire);
		owner = (CheckBox) findViewById(R.id.addCbOwner);
		photo = (ImageView) findViewById(R.id.addimgPhoto);
		btnAjouter = (Button) findViewById(R.id.btn_add_ajouter);
		// btnCurrency = (Button) findViewById(R.id.add_currency);
	
		/*
		 * Definition du string pour recup�rer le lien
		 */
		final String 	 urlProductNew = context.getResources().getString(R.string.lien)+ "api/product/new?json=" ;
		
		//http://pricy.me/web/app_dev.php/api/product/new?json=
		//http://pricy.me/web/app_dev.php/api/product/upload?id=
		
		
		final User user = new User();
		user.loadData(context);
		/* btnCurrency.setText(user.getCurrencyCustom());
		btnCurrency.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final CharSequence[] items = {"�", "$", "DH"};

				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setTitle("Choisir une devise");
				builder.setItems(items, new DialogInterface.OnClickListener() {
				    public void onClick(DialogInterface dialog, int item) {
				         btnCurrency.setText(items[item]);
				    }
				});
				AlertDialog alert = builder.create();
				alert.show();
			}
			
			
		});	*/
        
		
		btnAjouter.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				

				Log.e("INFOS", "Titre = "+titre.getText()+ " Prix = "+prix.getText()+ " Vendeur = " + owner.isChecked());
				
				boolean flag = true;
				
				if( titre.getText().toString().length() == 0 ){
					titre.setError(  context.getString(R.string.titleOfProduct) );
					flag = false;
				}
				if( prix.getText().toString().length() == 0 ){
					prix.setError( context.getString(R.string.priceOfProduct) );
					flag = false;
				}
				
				if( picture == null ){
					Toast.makeText(context, context.getString(R.string.MayaddPic), Toast.LENGTH_SHORT).show();
					flag = false;
				}
				if(flag){
					AlertDialog.Builder builder = new AlertDialog.Builder(context);
					builder.setTitle(context.getString(R.string.choiceCategori));
					CategoryIcon c = new CategoryIcon(0);
					final List<CategoryIcon> data = c.getAll(context);

			        CategoryChoiceAdapter adapter = new CategoryChoiceAdapter(context, data);
					builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog, final int item) {
					    	mProgress.setMessage(context.getString(R.string.Addproduct1));
							mProgress.show();
							
							new Thread() {
								
								@Override
								public void run() {
									Product product = new Product();
									product.setUser(user);
									product.setCategory(new Category(1));
									product.setTitle(titre.getText().toString());
									product.setPrice(Double.parseDouble(prix.getText().toString()));
									product.setCurrency("MAD");
									product.setAdress(user.getAdress());
									product.setOwner(owner.isChecked());
									product.setCategory(new Category(data.get(item).getId()));
									
							        try {
										
									// Create a new HttpClient and Post Header
						            HttpClient httpclient = new DefaultHttpClient();
						            HttpPost httppost = new HttpPost(urlProductNew+URLEncoder.encode(product.toJSON(), "UTF-8"));
						            Log.e("ULR",urlProductNew+URLEncoder.encode(product.toJSON(), "UTF-8"));
						                // Execute HTTP Post Request
						                HttpResponse response = httpclient.execute(httppost);
						                String productJson = EntityUtils.toString(response.getEntity());
						                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
						                Product p = (Product) gson.fromJson(productJson, Product.class);
						                
						                uploadPicture(""+p.getId());
						                // Save Product
						                //product.setId(Integer.parseInt(productId));
						                //product.setNow();
						                product.addProduct(context,p);
						                File sdCardDirectory = Environment.getExternalStorageDirectory();
						                File image = new File(sdCardDirectory, "product-"+p.getId()+".jpg");
						             // Encode the file as a PNG image.
						                FileOutputStream outStream;
						                try {

						                    outStream = new FileOutputStream(image);
						                    pictureThumb.compress(Bitmap.CompressFormat.JPEG, 100, outStream); 

						                    outStream.flush();
						                    outStream.close();
						                    mProgress.dismiss();
						                    hm.sendEmptyMessage(0);
						                } catch (FileNotFoundException e) {
						                    e.printStackTrace();
						                }
						                
							        } catch (UnknownHostException e) { 
							        	Log.e("ERROR", "2");
							        	// Save product locally
							        	saveProductEventually(product);
									} catch (HttpHostConnectException e) { 
										Log.e("ERROR", "3");
										// Save product locally
							        	saveProductEventually(product);
									} catch (ClientProtocolException e) { Log.e("ERROR", "4");
									} catch (IOException e) { Log.e("ERROR", "5");
						            }
								}

							}.start();
					    }
					});
					AlertDialog alert = builder.create();
					alert.show();
				}
				
			}
		});
		
		hm = new Handler() {
            public void handleMessage(Message m) {
            	Toast.makeText(context, context.getString(R.string.productAddSuccess), Toast.LENGTH_SHORT).show();
            	final Intent swipeList = new Intent(context, MyProductsActivity.class);
            	context.startActivity(swipeList);
            }
        };
	}

	public void setPhoto(Bitmap pictureThumb, Bitmap picture) {
		this.picture = picture;
		this.pictureThumb = pictureThumb;
		photo.setImageBitmap(pictureThumb);
	}
	
	private void uploadPicture(String id) throws ClientProtocolException, IOException{
		HttpClient httpClient = new DefaultHttpClient();
		    HttpPost postRequest = new HttpPost(context.getResources().getString(R.string.lien)+"api/product/upload?id="+id);
		    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
		    try{
		        ByteArrayOutputStream bos = new ByteArrayOutputStream();
		        picture.compress(CompressFormat.JPEG, 100, bos);
		        byte[] data = bos.toByteArray();
		        ByteArrayBody bab = new ByteArrayBody(data, "product-"+id+".jpg");
		        reqEntity.addPart("file", bab);
		    }
		    catch(Exception e){
		        reqEntity.addPart("picture", new StringBody(""));
		    }
		    postRequest.setEntity(reqEntity);       
		    HttpResponse response = httpClient.execute(postRequest);
		    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
		    String sResponse;
		    StringBuilder s = new StringBuilder();
		    while ((sResponse = reader.readLine()) != null) {
		        s = s.append(sResponse);
		    }
		    Log.e("UPLOAD", s.toString());
	}
	
	private void saveProductEventually(Product product) {
		
		 java.util.Date date= new java.util.Date();
		 Timestamp t = new Timestamp(date.getTime());
	    
		TempData td = new TempData();
         td.setType(TempData.PRODUCT);
         td.setUrl(product.toJSON());
         td.setData(""+t.getTime());
         td.push(this.context);
         
      // Save picture locally
         File sdCardDirectory = Environment.getExternalStorageDirectory();
         File image = new File(sdCardDirectory, "product-"+t.getTime()+".jpg");
         // Encode the file as a PNG image.
         FileOutputStream outStream;
         try {

             outStream = new FileOutputStream(image);
             pictureThumb.compress(Bitmap.CompressFormat.JPEG, 100, outStream); 

             outStream.flush();
             outStream.close();
             mProgress.dismiss();
             hm.sendEmptyMessage(0);
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
